var client = {};
var app = getApp();

// 选房大厅页需要用到
// 每批次多少人
var countPerBatch = 1;
// 自己的批次
var myBatchNo = -1;

var taskId;
var lockedHouseId;
var mineHouseId;
var taskType;

// 开盘信息轮询接口
client.openInfoAsk = function (that) {
  taskId = my.getStorageSync({ key: 'taskId' }).data;
  lockedHouseId = my.getStorageSync({ key: 'lockedHouseId' }).data;
  mineHouseId = my.getStorageSync({ key: 'mineHouseId' + taskId }).data;
  taskType = my.getStorageSync({ key: 'taskType' }).data;
  my.request({
    url: app.globalData.url + "878d3082-7b4f-41c0-9407-f1827fb8a841",
    method: "POST",
    headers: {
      "Access-Token": app.globalData.token
    },
    dataType: "json",
    success: function (res) {
      console.log("选房大厅 开盘信息轮询接口 openInfoAsk  " + JSON.stringify(res));
      if (res.data.succeed == 0) {
        var sellingStatus = "未开盘";
        var flagIsShow = true;
        // 是否进入开盘状态，显示当前顺序号
        var status_hidden = false;

        countPerBatch = res.data.data.countPerBatch;
        myBatchNo = res.data.data.myBatchNo;

        // 倒计时模块
        var timeBackground = "rgba(242,242,242,1)";
        var timeColor = "rgba(215,215,215,1)";
        var timeTips = "选" + taskType + "限时";
        var minute = res.data.data.limitTime;
        var second = 0;

        var canBuy = false;

        var taskId = my.getStorageSync({ key: 'taskId' }).data;
        switch (res.data.data.status) {
          // 当前任务状态 0-未开盘
          case 0:
            that.setData({
              minute: minute < 10 ? "0" + minute : minute,
              second: second < 10 ? "0" + second : second
            });
            return;
          // 当前任务状态  1-开盘中
          case 1:
            sellingStatus = "进行中";
            status_hidden = true;
            /**
             * 用户的状态
             *     0 - "没轮到自己的批次"
             *     1 - "选房中"
             *     2 - 已放弃"
             *     3 - 已选中"
             */
            switch (res.data.data.buyerStatus) {
              // 用户的状态 0 - "没轮到自己的批次"
              case 0:
                my.showToast({
                  content: taskType + "已开盘，请等待您的选" + taskType + "批次",
                  duration: 2000
                });
                break;
              // 用户的状态 1 - "选房中"
              case 1:
                // chooseStrategy==0代表可选多批次
                if (my.getStorageSync({ key: 'chooseStrategy' }).data == 0 && res.data.data.currentBatchNo > myBatchNo) {
                  myBatchNo = res.data.data.currentBatchNo;
                }
                if (res.data.data.currentBatchNo == myBatchNo) {
                  my.showToast({
                    content: "已轮到您的选" + taskType + "批次，请尽快选" + taskType,
                    duration: 2000
                  });

                  timeTips = "选" + taskType + "倒计时";
                  timeBackground = "linear-gradient(180deg,rgba(255,98,0,1) 0%,rgba(250,135,0,1) 100%)";
                  timeColor = "rgba(255,255,255,1)";
                  var miao = parseInt(res.data.data.leftMilliSecond / 1000);
                  minute = parseInt(miao / 60);
                  second = miao - minute * 60;

                  // 剩余时间大于0秒，才启动计时器，显示绿条；否则，不显示绿条，不启动计时器
                  if (miao > 0) {
                    flagIsShow = false;
                    // 切换启动下一个计时器
                    lastCountTimeId++;
                    client.countTime(minute, second, that);

                    canBuy = true;
                  } else {
                    // 剩余时间为0后，自己的锁定消失，购买关闭
                    my.setStorageSync({
                      key: 'lockedHouseId',
                      data: 0
                    });
                  }
                }
                break;
              // 用户的状态 2 - 已放弃"
              case 2:
                my.showToast({
                  content: "您已放弃选" + taskType + "，不能再次选" + taskType + "了",
                  duration: 2000
                });
                break;
              // 用户的状态 3 - 已选中"
              case 3:
                my.showToast({
                  content: "您已选中您的" + taskType + "，不能再次选" + taskType + "了",
                  duration: 2000
                });
                break;
            }
            // 当前楼盘的当前用户的选房状态
            my.setStorageSync({ key: 'buyerStatus' + taskId, data: res.data.data.buyerStatus });
            break;
          // 当前任务状态 2-已经结束
          case 2:
            sellingStatus = "已结束";
            // 状态为4，代表此楼盘选房已结束
            my.setStorageSync({ key: 'buyerStatus' + taskId, data: 4 });
            break;
        }
        that.setData({
          flagIsShow: flagIsShow,
          fullTime: res.data.data.limitTime,
          sellingStatus: sellingStatus,
          status_hidden: status_hidden,

          currentBatchNo: res.data.data.currentBatchNo,
          startNo: (res.data.data.currentBatchNo - 1) * countPerBatch + 1,
          endNo: res.data.data.currentBatchNo * countPerBatch,
          myBatchNo: myBatchNo,
          index: res.data.data.index,
          // 倒计时模块
          timeBackground: timeBackground,
          timeColor: timeColor,
          timeTips: timeTips,
          minute: minute < 10 ? "0" + minute : minute,
          second: second < 10 ? "0" + second : second,

          canBuy: canBuy
        });
      } else {
        app.errorHandling("开盘信息轮询失败：", res);
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      my.showToast({
        content: "网络错误：" + res.data.errorMsg,
        duration: 2000
      });
    },
    complete: function () { }
  });
};

// 本地缓存的房间数据
var roomList;
var that;
// 通过发送消息的方式，来判断websocket是否已连接
client.ifNeedWebsocket = function (that0, roomList0) {
  that = that0;
  roomList = roomList0;
  my.sendSocketMessage({
    data: '{"code":1}',
    success: () => {
      console.log("已有连接，无需再次建立连接");
    },
    fail: () => {
      console.log("连接没有，建立连接");
      connectSocket();
    }
  });
};

// 连接 websocket
function connectSocket() {
  // loginToken改为用token替代
  my.connectSocket({
    url: app.globalData.ipW + app.globalData.token,
    success: () => {
      console.log("连接成功");
    },
    fail: () => {
      console.log("连接失败");
    }
  });

  // 接收消息的时间
  var time = 0;
  // 刷新的时间
  var socketTime = 0;
  my.onSocketMessage(res => {
    console.log("onSocketMessage： " + res.data);
    // {"code":3,"data":{"currentBatch":1,"taskId":85,"currentBatchExpireMillis":6000000,"status":4}}
    // code:3,才是正常消息，taskId是当前任务，为了多任务开盘
    var websocketData = JSON.parse(res.data);
    if (websocketData.code == 3 && websocketData.data.taskId == taskId) {
      console.log("websocketData.data.status " + websocketData.data.status);
      // 如果status==4，就是更新批次状态。如果status==5，就是开盘结束。如果status:1、2、3，就是更新某个房间的购买状态。
      // status 消息类型 1 房源锁定 2 房源解锁 3 房源认购 4 换下一批次 5 结束选房
      // status 4 换下一批次
      if (websocketData.data.status == 4) {
        var currentBatch = websocketData.data.currentBatch;
        if (currentBatch == 1 && myBatchNo != 1) {
          my.showToast({
            content: taskType + "开盘，请等待您的选" + taskType + "批次",
            duration: 2000
          });
        }
        var flagIsShow = true;

        var timeTips = "选" + taskType + "限时";
        var timeBackground = "rgba(242,242,242,1)";
        var timeColor = "rgba(215,215,215,1)";
        var miao = parseInt(
          websocketData.data.currentBatchExpireMillis / 1000
        );
        var minute = parseInt(miao / 60);
        var second = miao - minute * 60;

        var canBuy = false;

        // 用户的状态 0 - "没轮到自己的批次" 1 - "选房中" 时，可以选房
        // 7月20号加入的逻辑，myTurn=true代表自己还没有选房
        var myTurn = false;
        // buyerStatus 为空，或者taskId不是当前任务，代表前一个状态是未开盘，收到此websocket后开盘了。
        var buyerStatus = my.getStorageSync({ key: 'buyerStatus' + taskId }).data;
        if (buyerStatus == null || buyerStatus == 0 || buyerStatus == 1) {
          myTurn = true;
        }

        console.log("my.getStorageSync({ key: 'chooseStrategy' }).data: " + my.getStorageSync({ key: 'chooseStrategy' }).data);
        // chooseStrategy==0代表可选多批次
        if (my.getStorageSync({ key: 'chooseStrategy' }).data == 0 && currentBatch >= myBatchNo && myTurn) {
          myBatchNo = currentBatch;
        }
        if ((currentBatch == myBatchNo) && myTurn) {
          my.showToast({
            content: "已轮到您的选" + taskType + "批次，请尽快选" + taskType,
            duration: 1000
          });

          flagIsShow = false;

          timeTips = "选" + taskType + "倒计时";
          timeBackground = "linear-gradient(180deg,rgba(255,98,0,1) 0%,rgba(250,135,0,1) 100%)";
          timeColor = "rgba(255,255,255,1)";

          // 切换启动下一个计时器
          lastCountTimeId++;
          client.countTime(minute, second, that);

          canBuy = true;
        } else if (currentBatch > myBatchNo && buyerStatus == 2) {
          // 代表放弃选房，错过选房批次
          my.showToast({
            content: "您已放弃选" + taskType + "，不能再次选" + taskType + "了",
            duration: 2000
          });
          my.setStorageSync({ key: 'buyerStatus' + taskId, data: 2 });
        }
        console.log("currentBatch: " + currentBatch);
        console.log("myBatchNo: " + myBatchNo);
        console.log("currentBatch == myBatchNo: " + (currentBatch == myBatchNo));
        console.log("myTurn: " + myTurn);
        that.setData({
          flagIsShow: flagIsShow,

          sellingStatus: "进行中",
          status_hidden: true,

          currentBatchNo: currentBatch,
          startNo: (currentBatch - 1) * countPerBatch + 1,
          endNo: currentBatch * countPerBatch,
          myBatchNo: myBatchNo,

          timeTips: timeTips,
          timeBackground: timeBackground,
          timeColor: timeColor,
          minute: minute < 10 ? "0" + minute : minute,
          second: second < 10 ? "0" + second : second,
          canBuy: canBuy
        });
        // 每一批次更新，被锁定的房源都要释放
        my.setStorageSync({
          key: 'lockedHouseId',
          data: 0
        });
      } else if (websocketData.data.status == 5) {
        // 如果status == 5，就是开盘结束。
        my.showToast({
          content: taskType + "开盘结束",
          duration: 1000
        });
        that.setData({
          flagIsShow: true,

          sellingStatus: "已结束",
          status_hidden: false,

          timeBackground: "rgba(242,242,242,1)",
          timeColor: "rgba(215,215,215,1)",

          canBuy: false
        });
        // 状态为4，代表此楼盘选房已结束
        my.setStorageSync({ key: 'buyerStatus' + taskId, data: 4 });
      } else {
        // {"code":3,"data":{"houseId":3727,"buyerName":"赵鹏*","currentBatch":1,"status":1,"currentBatchExpireMillis":300000}}
        // 如果status:1、2、3，就是更新某个房间的购买状态。
        for (var i = 0; i < roomList.length; i++) {
          if (roomList[i].id == websocketData.data.houseId) {
            // 已售状态不再改变，自己锁定不再改变
            if (roomList[i].status == 2 || roomList[i].status == 3 || roomList[i].status == 4) {
              break;
            }
            // status 消息类型 1 房源锁定 2 房源解锁 3 房源认购
            // websocket的status与roomList的status并不完全相同
            switch (websocketData.data.status) {
              case 1:
                roomList[i].status = 1;
                roomList[i].background = "rgba(255,116,116,1)";
                // 如果id与本地锁定id相同，则是本人锁定，字体置蓝
                if (roomList[i].id == lockedHouseId) {
                  roomList[i].status = 3;
                  roomList[i].color = "#2680EB";
                }
                break;
              case 2:
                roomList[i].status = 0;
                roomList[i].background = "rgba(255,255,255,1)";
                break;
              case 3:
                roomList[i].status = 2;
                roomList[i].background = "rgba(153,153,153,1)";
                // 如果id与本地购买id相同，则是本人已购，字体置蓝
                if (buyerStatus == 3 && roomList[i].id == mineHouseId) {
                  roomList[i].status = 4;
                  roomList[i].color = "#2680EB";
                }
                break;
            }

            console.log("更新的房间id：" + roomList[i].id);
            break;
          }
        }
        // 优化刷新频率为最快1秒刷新一次页面
        time = Date.parse(new Date());
        var betweenTime = time - socketTime;
        // 12秒时（12）	    刷新（并把刷新时间更新为12秒）
        // 12.1秒时（0.1）	不刷新（等待13秒时刷新，并把刷新时间更新为13秒）
        // 12.3秒时（-0.8）	不刷新（13秒刷新时已刷新此数据）
        // 13秒时（0）	    不刷新（等待14秒时刷新，并把刷新时间更新为14秒）
        // 如果距离上次刷新时间超过1秒，则刷新，并更新刷新时间。
        if (betweenTime >= 1000) {
          socketTime = Date.parse(new Date());
          that.setData({
            roomList: roomList
          });
          // 如果距离上次刷新时间小于1秒，大于等于0秒，则延迟到下一秒刷新，并更新刷新时间为上次刷新时间的下一秒。
        } else if (betweenTime >= 0) {
          var delayTime = 1000 - betweenTime;
          socketTime += 1000;
          setTimeout(function () {
            // 如果这时候用户没有切换单元，才能刷新房间状态。也就是刷新状态的时候，用户还没有切换单元.
            // 用户切换单元的时间戳要比最后一次接收消息的时间戳更早，更小。
            if (time > that.data.roomChange) {
              that.setData({
                roomList: roomList
              });
            }
          }, delayTime);
        }
        // 如果距离上次刷新时间小于0秒，则什么也不做。
      }
    }
  });

  // 心跳
  let promise = new Promise((resolve) => {
    let setTimer = setInterval(() => {
      my.sendSocketMessage({
        data: '{"code":1}',
        success: res => {
          console.log("数据发送！  " + JSON.stringify(res));
        },
        fail: () => {
          // my.showToast({
          //   content: "网络已断开！",
          //   duration: 1000
          // });
          resolve(setTimer);
        }
      });
    }, 60000);
  });
  promise.then(setTimer => {
    console.info("clearInterval");
    clearInterval(setTimer);
  });
};

// 为了实现每次启动倒计时，上次计时如果未到0，依然结束上次重置为网络剩余时间开始计时
var lastCountTimeId = 0;

// 分钟倒计时插件
client.countTime = function (minute, second, that) {
  var countTimeId = lastCountTimeId + 1;
  var Interval = setInterval(function () {
    // console.info(
    //   lastCountTimeId + " 进入 " + countTimeId + " second:  " + second
    // );
    // 如果重新启动倒计时，则当前的和之前的所有倒计时全部结束
    if (lastCountTimeId >= countTimeId) {
      console.log("如果重新启动倒计时，则当前的和之前的所有倒计时全部结束");
      clearInterval(Interval);
    }
    if (second > 0) {
      second--;
    } else if (minute > 0) {
      minute--;
      second = 59;
    } else {
      console.log("时间到");
      clearInterval(Interval);
      // 倒计时结束，绿条消失，true是隐藏显示
      that.setData({
        flagIsShow: true,
        canBuy: false
      });
      // 自己的锁定消失，购买关闭
      my.setStorageSync({
        key: 'lockedHouseId',
        data: 0
      });
    }
    // 倒计时提示对话框显示3秒
    var lastWarning = false;
    if (minute == 0 && (second == 30 || second == 29 || second == 28)) {
      lastWarning = true;
    }

    var second1 = second < 10 ? "0" + second : second;
    var minute1 = minute < 10 ? "0" + minute : minute;
    var time = minute1 + " : " + second1;
    that.setData({
      second: second1,
      minute: minute1,
      time: time,
      lastWarning: lastWarning
    });
  }, 1000);
};

module.exports = {
  client: client
};